package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

@RequiredArgsConstructor
public class SimpleRedisLock  implements ILock {

    private final String name;
    private final StringRedisTemplate redisTemplate;
    private static final String keyPrefix = "lock:";
    private static final String IDPrefix = UUID.randomUUID().toString(true)+"-";
    private static final DefaultRedisScript<Long> unlcokscript ;
    static {
        unlcokscript = new DefaultRedisScript<>();
        unlcokscript.setLocation(new ClassPathResource("unlock.lua"));
        unlcokscript.setResultType(Long.class);
    }

    @Override
    public boolean tryLock(long timeout ){
        // 获取线程标识
        String value  = Thread.currentThread().getId() + IDPrefix;
        // 获取锁
        Boolean success = redisTemplate.opsForValue().setIfAbsent(keyPrefix + name, value, timeout, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    @Override
    public void unlock() {
        // 调用lua脚本
        redisTemplate.execute(unlcokscript,
                Collections.singletonList(keyPrefix+name),
                IDPrefix+Thread.currentThread().getId());
    }



//    @Override
//    public void unlock() {
//        // 获取线程标识
//        String value  = Thread.currentThread().getId() + IDPrefix;
//        // 获取redis中的锁
//        String Id = redisTemplate.opsForValue().get(keyPrefix + name);
//        // 比较再释放
//        if(value.equals(Id)){ redisTemplate.delete(keyPrefix + name);}
//    }
}
